package com.amgl.mobike.mvp;

import android.app.Activity;

import com.google.gson.Gson;

import java.lang.ref.WeakReference;

import io.reactivex.Observable;
import io.reactivex.Observer;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.schedulers.Schedulers;
import okhttp3.MediaType;
import okhttp3.RequestBody;

/**
 * Created by 阿木 on 2017/4/18.
 */

public class BasePresenter<V> {
    private WeakReference<V> mView;
    private Activity mActivity;

    public BasePresenter(V view) {
        mView = new WeakReference<V>(view);
    }

    protected V getView() {
        if (mView != null) {
            return mView.get();
        }
        return null;
    }

    protected void onCreate(Activity activity) {
        mActivity = activity;
    }

    protected void onDestroy(Activity activity) {
        mActivity = null;
    }

    protected void doRequest(Observable observable, Observer observer) {
        observable.subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(observer);
    }

    public static RequestBody createRequestBody(Object params) {
        Gson gson = new Gson();
        String str = gson.toJson(params);
        RequestBody body = RequestBody.create(MediaType.parse("application/json; charset=utf-8"), str);
        return body;
    }
}
